<!-- 新增编辑员工 -->
<template>
  <div>
    <el-dialog
      :title="isAdd == 1 ? '新增员工' : '修改员工'"
      :visible.sync="addEditVisible"
    >
      <el-form
        class="formView"
        ref="updateForm"
        :model="formdata"
        :rules="rules"
        label-position="right"
        label-width="100px"
      > 
        <el-form-item label="员工姓名:" prop="fullName">
          <el-input
            v-model.trim="formdata.fullName"
            clearable
            placeholder="姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="mobile">
          <el-input
            v-model.trim="formdata.mobile"
            type="number"
            max='11'
            clearable
            placeholder="手机号"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="工号:" prop="userNo">
          <el-input
            v-model="formdata.userNo"
            clearable
            placeholder="工号"
          ></el-input>
        </el-form-item> -->
        <el-form-item label="选择部门" prop="deptIds">
          <el-cascader :props="propss" :options="deptList" v-model="formdata.deptIds" clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="选择角色:" prop="roleIds">
          <el-select v-model="formdata.roleIds" clearable placeholder="请选择角色">
            <el-option
              v-for="item in roleList"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId">
              </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="登录密码:" prop="password" v-if="isAdd == 1">
          <el-input
            v-model="formdata.password"
            placeholder="登录密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="登录名:" prop="username">
          <el-input
            v-model.trim="formdata.username"
            placeholder="登录名"
          ></el-input>
        </el-form-item>
        
      </el-form>
      <div slot="footer">
        <el-button @click="addEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('updateForm')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { addUser , updateUser , getRolePage , getDeptList} from '@/api/rightsManage'
export default {
  components: {},
  computed: {
    ...mapGetters(['name', 'userInfo']),
    isRoleAdmin(){
      return this.userInfo && this.userInfo.roleCodeList && this.userInfo.roleCodeList.includes('1001')
    }
  },
  props: {
    isAdd: {
      type: Number,
      default() {
        return 1
      }
    },
    detailData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      addEditVisible: false,
      roleList:[],
      deptList:[],
      lineList:[],
      formdata:{
          deptId: '',
          fullName: '',
          mobile:'',
          password: '',
          roleIds:'',
          userNo:'',
          state:0,
          username:'',
          deptIds:[]
      },
      rules: {
        fullName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
        ],
        username: [
          { required: true, message: '请输入登录名', trigger: 'blur' },
        ],
        // userNo: [
        //   { required: true, message: '请输入工号', trigger: 'blur' },
        // ],
        roleIds:[
          { required: true, message: '请选择角色', trigger: 'change' },
        ],
        deptIds: [
          { type: 'array', required: true, message: '请选择部门', trigger: 'change' },
        ]
      },
      propss: {
        lazy: false,
        value:'deptId',
        label:'deptName',
        children:'childrens',
        expandTrigger: 'hover',
        checkStrictly: true
      }
    }
  },
  created() {},
  mounted() {},
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.onSubmit()
        } else {
          return false
        }
      })
    },
    onSubmit() {
      console.log(this.formdata)
      if(this.isAdd == 1){
        addUser(this.formdata).then(res => {
            console.log(res)
            this.$message({
                message: this.isAdd == 1 ? '新增成功' : '修改成功',
                type: 'success'
            })
            this.$parent.getDataList()
            this.resetForm('updateForm')
        })
      }else{
        updateUser(this.formdata).then(res => {
            console.log(res)
            this.$message({
                message: this.isAdd == 1 ? '新增成功' : '修改成功',
                type: 'success'
            })
            this.$parent.getDataList()
            this.resetForm('updateForm')
        })  
      }
    
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.formdata = {
        deptId: '',
        fullName: '',
        mobile:'',
        password: '',
        roleIds:'',
        userNo:'',
        state:0,
        username:'',
        deptIds:[]
      }
      this.addEditVisible = false
    },
    // 获取角色列表
    getRoleList(){
      getRolePage({}).then(res => {
        this.roleList = res.data
      })
    },
    // 获取部门列表
    getDeptList(){
      getDeptList({}).then(res => {
        this.lineList = res.data
        this.deptList = this.listConvertTree(res.data)
        if(this.isAdd == 2){
          this.formdata.deptIds = this.getChildrenIds(this.detailData.deptId)
        }
      })
    },
    // 获取部门 parentIds
    getChildrenIds(deptId){
      let Root = JSON.parse(JSON.stringify(this.lineList))
      let list = []
      let findParentId = (root, deptId) =>{
        root.forEach((current , index) =>{
          if(current.deptId == deptId && current.parentId > 0){
            list.push(current.parentId)
            let temp = JSON.parse(JSON.stringify(root.slice(0, index).concat(root.slice(index + 1, root.length))))
            findParentId(temp, current.parentId)
          }
        })
      }
      findParentId(Root,deptId)
      list.reverse()
      list.push(deptId)
      return list     
    },
    // 线性转树结构
    listConvertTree(data) {
     let parents = [
      ]

      //有父节点的数据
      let childrens = data.filter(
        value => value.parentId !== 'undefined' && value.parentId != null
      )
      
      let childrensCopy = JSON.parse(JSON.stringify(childrens))
      let childrensCopy1 =JSON.parse(JSON.stringify(childrensCopy))
      childrens.forEach((item1,index1) => {
        childrensCopy1.forEach((item2,index2)=>{
          if(item1.parentId == item2.deptId && index1 != index2) {
      
            childrensCopy.splice(childrensCopy.indexOf(item2),1)
  
          }
        })
      })
       
      parents = childrensCopy
     
      // console.log(childrens)
      //定义转换方法的具体实现
      let translator = (parents, childrens) => {
        //遍历父节点数据
        parents.forEach(parent => {
          //遍历子节点数据
          childrens.forEach((current, index) => {
            //此时找到父节点对应的一个子节点
            if (current.parentId === parent.deptId) {
              //对子节点数据进行深复制，这里只支持部分类型的数据深复制，对深复制不了解的童靴可以先去了解下深复制
              let temp = JSON.parse(JSON.stringify(childrens))
              //让当前子节点从temp中移除，temp作为新的子节点数据，这里是为了让递归时，子节点的遍历次数更少，如果父子关系的层级越多，越有利
              temp.splice(index, 1)
              //让当前子节点作为唯一的父节点，去递归查找其对应的子节点
              translator([current], temp)
              //把找到子节点放入父节点的childrens属性中
              typeof parent.childrens !== 'undefined' ? parent.childrens.push(current) : (parent.childrens = [current])
            }
            
          })
         
          
        })
      }
      //调用转换方法
      translator(parents, childrens)
      console.log('parents',parents)
      //返回最终的结果
      return parents
    } 
  },
  watch: {
    addEditVisible: {
        deep: true,
        handler(now, old) {
            if(now){
                this.getRoleList()
                this.getDeptList()
                if(this.isAdd == 2){
                  this.formdata.username = this.detailData.userName
                  this.formdata = Object.assign({},this.formdata , this.detailData)
                  this.formdata.roleIds = this.detailData.roleId
                }
            }else{
                this.resetForm('updateForm')
            }

        }
    },
    'formdata.deptIds':{
        deep: true,
        handler(now, old) {
          if(now){
            this.formdata.deptId = now[now.length-1]
          }else{
            this.formdata.deptId = ''
          }
        }
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep {
  .el-dialog{
    width: 500px;
    border-radius: 10px;
  }
  .el-dialog__title {
    font-size: 16px;
  }
  .el-input{
    width: 250px;
  }
  .el-dialog__body {
    padding-top: 0;
    padding-bottom: 0px;
  }
  .el-form {
    padding: 10px 0;
  }
  .el-input__inner {
    height: 35px;
    line-height: 35px;
  }
  .el-form-item {
    margin-bottom: 15px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .el-dialog__footer {
    padding-top: 10px;
    padding-bottom: 10px;
    border-top: 1px solid #eee;
  }
}
.formView {
  border-top: 1px solid #eee;
  .sortInput {
    width: 100px;
  }
}
</style>